package com.nowcoder.community.contorller;

import com.nowcoder.community.util.CommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/alpha")
public class AlphaController {

    @GetMapping("/hello")
    @ResponseBody
    public String hell(){
        return "Hello";
    }

//    @GetMapping("/greeting")
//    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
//        model.addAttribute("name", name);
//        return "greeting";
//    }

//    @GetMapping("/greeting")
//    public ModelAndView greeting(@RequestParam(name="name", required=false, defaultValue="World") String name) {
//        ModelAndView mad = new ModelAndView();
//        mad.addObject("name",name);
//        mad.setViewName("greeting");
//        return mad;
//    }

    @GetMapping("/test")
    @ResponseBody
    public String test(String name) {
        return name;
    }

    @GetMapping("/cookie/set")
    @ResponseBody
    public String setCookie(HttpServletResponse response){
        //创建cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        //设置cookie生效范围
        cookie.setPath("/community/alpha");
        //设置cookie的生存时间
        cookie.setMaxAge(60*10);
        //发送cookie
        response.addCookie(cookie);

        return "set cookie";
    }

    @GetMapping("/cookie/get")
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){
        return code;
    }


    @GetMapping("/session/set")
    @ResponseBody
    public String setsession(HttpSession session){

        session.setAttribute("id","101");
        session.setAttribute("name","saber");

        return "set session";
    }

    @GetMapping("/session/get")
    @ResponseBody
    public String getCookie(HttpSession session){
        return session.getAttribute("id")+"---"+session.getAttribute("name");
    }

    //ajax
    @PostMapping("/ajax")
    @ResponseBody
    public String testAjax(String name ,int age){
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "success");
    }
}
